/*
 * Check whether one array is a non-strict subset of another
 *
 * Copyright 2023 Odin Kroeger.
 *
 * This file is part of suCGI.
 *
 * suCGI is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * suCGI is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General
 * Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with suCGI. If not, see <https://www.gnu.org/licenses/>.
 */

#define _XOPEN_SOURCE 700

#include <assert.h>
#include <stdbool.h>
#include <stddef.h>

#include "array.h"
#include "types.h"

/* NOLINTBEGIN(readability-suspicious-call-argument); clear enough */

bool
array_is_sub(const void *const sub,
             const size_t sublen, const size_t subwidth,
             const void *const super,
             const size_t superlen, const size_t superwidth,
             const CompFn cmp)
{
    assert(sub != NULL);
    assert(subwidth > 0U);
    assert(super != NULL);
    assert(superwidth > 0U);

    /* cppcheck-suppress misra-c2012-11.5; alignment is not an issue here */
    const char *ptr = (const char *) sub;

    for (size_t i = 0U; i < sublen; ++i) {
        const void *elem = array_find(ptr, super, superlen, superwidth, cmp);
        if (elem == NULL) {
            return false;
        }

        /* cppcheck-suppress [misra-c2012-10.3, misra-c2012-18.4] */
        ptr += superwidth;
    }

    return true;
}

/* NOLINTEND(readability-suspicious-call-argument) */
